/**
 * @file 浏览器上下文右键菜单（编辑/链接/图片/检查/翻译）
 */
import type { ContextMenuParams, WebContents } from 'electron'
import { BrowserManager } from '#/browser'
import { saveImageAsFromURL } from '#/utils/image'
import { getMenuIcon } from '#/utils/menuIcons'
import { clipboard, Menu, MenuItem } from 'electron'
import { LANGUAGE_CONFIG, type SupportedLanguage } from '~shared/constants'
import { systemState } from 'global-state'

// i18n 标签
type BrowserMenuLabels = {
  CUT: string
  COPY: string
  PASTE: string
  SELECT_ALL: string
  RELOAD: string
  OPEN_LINK: string
  OPEN_IN_NEW_TAB: string
  COPY_LINK: string
  COPY_IMAGE: string
  SAVE_IMAGE_AS: string
  TRANSLATE_PAGE: string
  SHOW_ORIGINAL: string
  INSPECT: string
  OPEN_SELECTED_LINKS_IN_NEW_GROUP: string
}

function getCurrentLanguage(): SupportedLanguage {
  const lang = systemState.state.language as SupportedLanguage | undefined
  const supported = LANGUAGE_CONFIG.SUPPORTED_LANGUAGES as readonly string[]
  return supported.includes(lang ?? '')
    ? (lang as SupportedLanguage)
    : (LANGUAGE_CONFIG.DEFAULT_LANGUAGE as SupportedLanguage)
}

function getBrowserMenuLabels(lang: SupportedLanguage = getCurrentLanguage()): BrowserMenuLabels {
  if (lang === 'zhHans') {
    return {
      CUT: '剪切',
      COPY: '复制',
      PASTE: '粘贴',
      SELECT_ALL: '全选',
      RELOAD: '刷新',
      OPEN_LINK: '在新窗口中打开链接',
      OPEN_IN_NEW_TAB: '在新标签页打开',
      COPY_LINK: '复制链接',
      COPY_IMAGE: '复制图片',
      SAVE_IMAGE_AS: '图片另存为',
      TRANSLATE_PAGE: '翻译该页面',
      SHOW_ORIGINAL: '回到原文',
      INSPECT: '检查元素',
      OPEN_SELECTED_LINKS_IN_NEW_GROUP: '新分组打开选择的链接'
    }
  }
  return {
    CUT: 'Cut',
    COPY: 'Copy',
    PASTE: 'Paste',
    SELECT_ALL: 'Select All',
    RELOAD: 'Reload',
    OPEN_LINK: 'Open link in new window',
    OPEN_IN_NEW_TAB: 'Open in new tab',
    COPY_LINK: 'Copy link',
    COPY_IMAGE: 'Copy image',
    SAVE_IMAGE_AS: 'Save image as…',
    TRANSLATE_PAGE: 'Translate this page',
    SHOW_ORIGINAL: 'Show Original',
    INSPECT: 'Inspect Element',
    OPEN_SELECTED_LINKS_IN_NEW_GROUP: 'Open selected links in new group'
  }
}

function addTranslateMenuItem(
  menu: Menu,
  webContents: WebContents,
  labels: BrowserMenuLabels,
  tab?: F2.tab.Entity
): void {
  const state = tab?.state.translation
  const isTranslated = state === 'translated'
  const isTranslating = state === 'translating'
  const label = isTranslated
    ? `${labels.SHOW_ORIGINAL} (&T)(T)`
    : `${labels.TRANSLATE_PAGE} (&T)(T)`

  menu.append(
    new MenuItem({
      label,
      icon: getMenuIcon('TRANSLATE_PAGE'),
      enabled: !isTranslating,
      click: () => {
        if (isTranslated) {
          webContents.send('restore-original')
          return
        }
        let targetLanguage = systemState.state.translationLanguage
        if (!targetLanguage) {
          targetLanguage = String(systemState.state.language ?? 'en')
          if (targetLanguage === 'zhHans') targetLanguage = 'zh-cn'
        }
        webContents.send('translate-page', targetLanguage)
      }
    })
  )
}

function addLinkMenuItems(
  menu: Menu,
  webContents: WebContents,
  linkURL: string,
  labels: BrowserMenuLabels
): void {
  menu.append(
    new MenuItem({
      label: `${labels.OPEN_IN_NEW_TAB} (&N)(N) `,
      icon: getMenuIcon('OPEN_IN_NEW_TAB'),
      click: () => {
        try {
          const windows = BrowserManager.getInstance().getWindowByWebContents(webContents)
          windows.tabManager.createTabs('top', linkURL)
        } catch (error) {
          console.error('在新标签页打开失败:', error)
        }
      }
    })
  )
  menu.append(
    new MenuItem({
      label: `${labels.COPY_LINK} (&C)(C)`,
      icon: getMenuIcon('COPY_LINK'),
      click: () => {
        try {
          clipboard.writeText(linkURL)
        } catch (error) {
          console.error('复制链接失败:', error)
        }
      }
    })
  )
  menu.append(
    new MenuItem({
      label: `${labels.OPEN_LINK} (&W)(W)`,
      icon: getMenuIcon('OPEN_LINK'),
      click: () => {
        BrowserManager.getInstance().createNewWindow(linkURL)
      }
    })
  )
}

function addImageMenuItems(
  menu: Menu,
  webContents: WebContents,
  params: ContextMenuParams,
  labels: BrowserMenuLabels
): void {
  const srcURL = params.srcURL
  if (!srcURL) return

  menu.append(
    new MenuItem({
      label: `${labels.COPY_IMAGE} (&C)(C)`,
      icon: getMenuIcon('COPY_IMAGE'),
      click: async () => {
        webContents.copyImageAt(params.x, params.y)
      }
    })
  )

  menu.append(
    new MenuItem({
      label: `${labels.SAVE_IMAGE_AS} (&S)(S)`,
      icon: getMenuIcon('SAVE_IMAGE_AS'),
      click: async () => {
        try {
          await saveImageAsFromURL(webContents, srcURL)
        } catch (error) {
          console.error('图片另存为失败:', error)
        }
      }
    })
  )
}

function addInspectMenuItem(
  menu: Menu,
  webContents: WebContents,
  x: number,
  y: number,
  labels: BrowserMenuLabels
): void {
  menu.append(
    new MenuItem({
      label: `${labels.INSPECT}`,
      icon: getMenuIcon('INSPECT'),
      click: () => {
        if (webContents.isDevToolsOpened()) {
          webContents.closeDevTools()
        } else {
          webContents.openDevTools()
        }
      }
    })
  )
}

/**
 * 从选中的内容中提取所有链接
 */
async function extractLinksFromSelection(webContents: WebContents): Promise<string[]> {
  try {
    const links = await webContents.executeJavaScript(`
      (() => {
        const selection = window.getSelection();
        if (!selection || selection.rangeCount === 0) return [];

        const range = selection.getRangeAt(0);
        const container = range.cloneContents();
        const anchorElements = container.querySelectorAll('a[href]');

        const urls = Array.from(anchorElements)
          .map(a => a.href)
          .filter(href => href && (href.startsWith('http://') || href.startsWith('https://')));

        return [...new Set(urls)]; // 去重
      })();
    `)
    return links || []
  } catch (error) {
    console.error('提取链接失败:', error)
    return []
  }
}

async function addSelectedLinksMenuItem(
  menu: Menu,
  webContents: WebContents,
  labels: BrowserMenuLabels
): Promise<void> {
  // 先提取链接，如果没有链接就不添加菜单项
  const links = await extractLinksFromSelection(webContents)
  if (links.length === 0) {
    return
  }

  const MAX_LINKS = 50
  const isOverLimit = links.length > MAX_LINKS

  // 在菜单标签中显示链接数量，如果超过限制则显示提示
  const lang = getCurrentLanguage()
  const labelWithCount = isOverLimit
    ? lang === 'zhHans'
      ? `${labels.OPEN_SELECTED_LINKS_IN_NEW_GROUP} (${links.length}，超过限制)`
      : `${labels.OPEN_SELECTED_LINKS_IN_NEW_GROUP} (${links.length}, exceeds limit)`
    : `${labels.OPEN_SELECTED_LINKS_IN_NEW_GROUP} (${links.length}) (&G)(G)`

  menu.append(
    new MenuItem({
      label: labelWithCount,
      icon: getMenuIcon('OPEN_IN_NEW_TAB'),
      enabled: !isOverLimit, // 超过限制时禁用
      click: async () => {
        try {
          console.log('提取到的链接:', links)
          // 通过 BrowserManager 获取当前窗口的 tabManager，然后调用 createTabGroup
          const window = BrowserManager.getInstance().getWindowByWebContents(webContents)
          window.tabManager.createTabGroup(links)
        } catch (error) {
          console.error('打开选中链接失败:', error)
        }
      }
    })
  )
}

async function buildBrowserContextMenu(
  webContents: WebContents,
  params: ContextMenuParams,
  tab?: F2.tab.Entity
): Promise<Menu> {
  const menu = new Menu()
  const labels = getBrowserMenuLabels()

  if (params.editFlags.canCut) {
    menu.append(
      new MenuItem({ label: `${labels.CUT} (&T)(T)`, role: 'cut', icon: getMenuIcon('CUT') })
    )
  }
  if (params.editFlags.canCopy) {
    menu.append(
      new MenuItem({ label: `${labels.COPY} (&C)(C)`, role: 'copy', icon: getMenuIcon('COPY') })
    )
  }
  if (params.editFlags.canPaste) {
    menu.append(
      new MenuItem({ label: `${labels.PASTE} (&P)(P)`, role: 'paste', icon: getMenuIcon('PASTE') })
    )
  }
  menu.append(
    new MenuItem({
      label: `${labels.SELECT_ALL} (&A)(A)`,
      role: 'selectAll',
      icon: getMenuIcon('SELECT_ALL')
    })
  )

  menu.append(new MenuItem({ type: 'separator' }))

  menu.append(
    new MenuItem({
      label: `${labels.RELOAD}  (&L)(L)`,
      icon: getMenuIcon('RELOAD'),
      click: () => webContents.reload()
    })
  )

  if (params.linkURL) addLinkMenuItems(menu, webContents, params.linkURL, labels)
  if (params.srcURL) addImageMenuItems(menu, webContents, params, labels)

  // 当有选中内容时，检查是否包含链接，如果有则添加"新分组打开选择的链接"菜单项
  if (params.selectionText && params.selectionText.trim().length > 0) {
    await addSelectedLinksMenuItem(menu, webContents, labels)
  }

  if (tab && tab.id > 0) {
    addTranslateMenuItem(menu, webContents, labels, tab)
  }
  menu.append(new MenuItem({ type: 'separator' }))

  addInspectMenuItem(menu, webContents, params.x, params.y, labels)

  return menu
}

export function createContextMenu(webContents: WebContents, data?: F2.tab.Entity): void {
  webContents.on('context-menu', async (event, params) => {
    event.preventDefault()
    const menu = await buildBrowserContextMenu(webContents, params, data)
    menu.popup()
  })
}
